package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.nursing.service.IWechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description WechatServiceImpl
 * @Author qiyuan
 * @Date 2025-07-22
 */
@Service
public class WechatServiceImpl implements IWechatService {

    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.appSecret}")
    private String appSecret;

    /**
     * 获取微信openid
     *
     * @param code
     */
    @Override
    public String getOpenId(String code) {
        //1.设置4个请求参数
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("appid", appId);
        paramsMap.put("secret", appSecret);
        paramsMap.put("js_code", code);
        //paramsMap.put("grant_type", "authorization_code");上面路径已经包含

        //2.调用微信接口获取openid，获取返回的json数据
        String json = HttpUtil.get(REQUEST_URL, paramsMap);

        //3.把json数据转换成map对象
        //JSONObject bean = JSONUtil.parseObj(result);
        Map <String,Object>  bean = JSONUtil.toBean(json, Map.class);

        //4.获取map对象里的openid并返回
        //判断是否有错误码，若有则抛出异常获取失败
        if (bean.get("errcode") != null){
            throw new ServiceException(bean.get("errmsg").toString());
        }


        return bean.get("openid").toString();
    }

    /**
     * 获取微信用户手机号
     *
     * @param phoneCode
     */
    @Override
    public String getPhoneNumber(String phoneCode) {

        //1.设置参数
        String accessToken = getAccessToken();
        String url = PHONE_REQUEST_URL +accessToken;

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", phoneCode);

        //2.调用微信接口获取phone，获取返回的json数据
        String json = HttpUtil.post(url, JSONUtil.toJsonStr(paramMap) );

        //3.把json数据转换成map对象
        JSONObject  bean = JSONUtil.toBean(json, JSONObject.class);

        //4.获取map对象里的openid并返回
        //判断是否有错误码是否为0，不为0则抛出异常获取失败
        if (bean.get("errcode") != null && !bean.get("errcode").toString().equals("0") ){
            throw new ServiceException(bean.get("errmsg").toString());
        }


        return bean.getJSONObject("phone_info").get("phoneNumber").toString();

    }

    /**
     * 获取微信接口访问凭证
     */
    private String getAccessToken() {
        //1.设置请求参数
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("appid", appId);
        paramsMap.put("secret", appSecret);

        //paramsMap.put("grant_type", "client_credential");上面路径已经包含

        //2.调用微信接口获取openid，获取返回的json数据
        String json = HttpUtil.get(TOKEN_URL, paramsMap);

        //3.把json数据转换成map对象
        //JSONObject bean = JSONUtil.parseObj(result);
        Map <String,Object>  bean = JSONUtil.toBean(json, Map.class);

        //4.获取map对象里的openid并返回
        //判断是否有错误码，若有则抛出异常获取失败
        if (bean.get("errcode") != null){
            throw new ServiceException(bean.get("errmsg").toString());
        }


        return bean.get("access_token").toString();


    }
}
